package cn.parllay.dingdangproject.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by sunny on 2017/8/17.
 */

public class NetWorkUtils {

    private static final String TAG = "NetWorkUtils";

    //接收数据回调接口
    public interface OnRequestListener<T> {
        void onSuccess(T t);

        void onError(String errorMsg);
    }


    //获取UI线程
    public static void runOnUiThread(Runnable runnable) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            runnable.run();
        } else {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(runnable);
        }
    }

    //GET请求
    public static void doGET(final String url, final HashMap<String, String> params,
                             final Class cls, final OnRequestListener listener) {
        OkHttpUtils.get().url(url).params(params).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {

                Log.e(TAG, s);
                Object bean = jsonToBean(s, cls);
                listener.onSuccess(bean);
            }
        });
    }
    //GET请求
    public static void doTestGET(final String url, final String testData, final HashMap<String, String> params,
                                 final Class cls, final OnRequestListener listener) {
        OkHttpUtils.get().url(url).params(params).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {

                Log.e(TAG, "测试数据: "+testData.toString());
                Object bean = jsonToBean(testData, cls);
                listener.onSuccess(bean);
            }
        });
    }

    public static void doGET(final String url, final HashMap<String, String> params,
                             final Class cls, Object tag, final OnRequestListener listener) {
        OkHttpUtils.get().url(url).params(params).tag(tag).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {

                Log.e(TAG, s);
                Object bean = jsonToBean(s, cls);
                listener.onSuccess(bean);
            }
        });
    }

    //POST请求
    public static void doPOST(final String url, final HashMap<String, String> params,
                              final Class cls, final OnRequestListener listener) {
        OkHttpUtils.post().url(url).params(params).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {

                Object bean = jsonToBean(s, cls);
                listener.onSuccess(bean);
            }
        });
    }

    public static void doPOST(final String url, final HashMap<String, String> params,
                              final StringCallback stringCallback) {
        OkHttpUtils.post().url(url).params(params).build().execute(stringCallback);

    }

    public static void doPostJson(final String url, Object object,
                                  final StringCallback stringCallback) {
        Log.e(TAG,"postJSON: " + new Gson().toJson(object));
        OkHttpUtils
                .postString()
                .url(url)
                .content(new Gson().toJson(object))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(stringCallback);

    }

    public static void doPostJson(final String url, final Object params, final Class clz,
                                  final OnRequestListener listener) {
        Log.e(TAG,"postJSON: " + new Gson().toJson(params));
        OkHttpUtils
                .postString()
                .url(url)
                .content(new Gson().toJson(params))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(String s, int i) {
                        Object bean = jsonToBean(s, clz);
                        if(listener != null) {
                            listener.onSuccess(bean);
                        }
                    }
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        if(listener != null) {
                            listener.onError(e.getMessage());
                        }
                    }
                });

    }
    public static void doPostJsonTest(final String url, final Object params, final String testData, final Class clz,
                                      final OnRequestListener listener) {
        Log.e(TAG,"postJSON: " + new Gson().toJson(params));
        OkHttpUtils
                .postString()
                .url(url)
                .content(new Gson().toJson(params))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(String s, int i) {
                        Log.e(TAG, "返回的任务列表"+ s);
                        Object bean = jsonToBean(testData, clz);
                        if(listener != null) {
                            listener.onSuccess(bean);
                        }
                    }
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        if(listener != null) {
                            listener.onError(e.getMessage());
                        }
                    }
                });

    }

    /**
     * 从服务器请求数据
     *
     * @param url
     * @param params
     * @return
     */
    private static void makeCall(String url, HashMap<String, String> params, Class cls, final OnRequestListener listener) {
        try {
            url = url + formatQueryString(params);
            Response response = OkHttpUtils
                    .get()
                    .url(url)
                    .build()
                    .execute();
            if (response.isSuccessful()) {

                String json = response.body().string();
                final Object bean = jsonToBean(json, cls);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listener.onSuccess(bean);
                    }
                });

            }
        } catch (IOException e) {
            listener.onError(e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 获取查询字符串
     *
     * @param params
     * @return
     */
    private static String formatQueryString(HashMap<String, String> params) {
        Set keys = params.keySet();
        Iterator iterator = keys.iterator();
        StringBuilder queryStringBuilder = new StringBuilder();
        queryStringBuilder.append("?");
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            queryStringBuilder.append(String.format("%s=%s&", key, params.get(key)));
        }

        String queryString = queryStringBuilder.toString();
        queryString = queryString.substring(0, queryString.length() - 1);
        return queryString;

    }

    /**
     * 将json结果解析成bean对象
     *
     * @param jsonResult
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(String jsonResult, Class<T> clz) {
        Gson gson = new Gson();
        T t = gson.fromJson(jsonResult, clz);

        return t;
    }
}
